# coding=utf-8
import random
import time
from django.core import signing
import hashlib
from django.core.cache import cache
from datetime import datetime
import uuid

HEADER = {'typ': 'JWP', 'alg': 'default'}
KEY = 'MENg_xIANG!!!'
SALT = 'Docloud'
TIME_OUT = 120 * 24 * 60 * 60  # 60min


def encrypt(obj):
    """加密"""
    value = signing.dumps(obj, key=KEY, salt=SALT)
    value = signing.b64_encode(value.encode()).decode()
    return value


def decrypt(src):
    """解密"""
    src = signing.b64_decode(src.encode()).decode()
    raw = signing.loads(src, key=KEY, salt=SALT)
    print(type(raw))
    return raw


def create_token(uid, username, password):
    """生成token信息"""
    # 1. 加密头信息
    header = encrypt(HEADER)
    # 2. 构造Payload
    payload = {"username": username, "password": password, "id": random.randint(999999, 1000000), "iat": time.time()}
    payload = encrypt(payload)
    # 3. 生成签名
    md5 = hashlib.md5()
    md5.update(("%s.%s" % (header, payload)).encode())
    signature = md5.hexdigest()
    # 存储到缓存中
    utoken = uid
    
    token = "%s==%s" % (utoken, str(uuid.uuid1())[1:5] + signature)
    cache.set(utoken, signature, TIME_OUT)
    return token


def get_payload(token):
    payload = str(token).split('.')[1]
    payload = decrypt(payload)
    return payload


# 通过token获取用户名
def get_username(token):
    payload = get_payload(token)
    return payload['username']
    pass


def check_token(token):
    username = get_username(token)
    last_token = cache.get(username)
    print(last_token)
    if last_token:
        if last_token == token:
            cache.set(username, token, TIME_OUT)
            return True
    return False
